from collections import defaultdict

from django.db.models import Count, F, Avg
from django.http import JsonResponse
from risk.models import *


def app_point(request):
    industry = request.GET.get("industry")
    response = {"data": {}}

    response["data"]['enterpriseTotal'] = Pingfen.objects.filter(行业=industry).values("企业名称").distinct().count()

    response["data"]['enterpriseDistrict'] = list(Pingfen.objects.filter(行业=industry).values("辖区")
                                                  .annotate(count=Count("企业名称", distinct=True)).values_list("辖区",
                                                                                                                "count"))

    # TODO 15
    res1 = {"A": 0, "B": 0, "C": 0, "D": 0}
    res2 = list(Pingfen.objects.filter(行业=industry, 抽检年度=2022).values("评分等级")
                .annotate(count=Count("企业名称", distinct=True)).values_list("评分等级", "count"))
    for i in res2:
        res1[i[0]] = i[1]
    response["data"]['grade'] = [(k, v) for k, v in res1.items()]


    tmp = list(Pingfen.objects.filter(行业=industry).values('辖区', '抽检年度').annotate(
        avg_score=Avg(F('产品风险因素') + F('企业通用信用风险因素') + F('企业质量信用风险因素'))))
    tmp1 = list(Pingfen.objects.filter(行业=industry).values('抽检年度').annotate(
        avg_score=Avg(F('产品风险因素') + F('企业通用信用风险因素') + F('企业质量信用风险因素'))))
    res = dict()
    for i in tmp:
        if i["辖区"] not in res:
            res[i["辖区"]] = {}
        res[i["辖区"]][i["抽检年度"]] = i["avg_score"]
    res["厦门市"] = {}
    for i in tmp1:
        res["厦门市"][i["抽检年度"]] = i["avg_score"]
    response["data"]["trend"] = res


    tmp = list(Pingfen.objects.filter(行业=industry).values('辖区', '抽检年度', '评分等级').annotate(count=Count("id")))
    tmp1 = list(Pingfen.objects.filter(行业=industry).values('抽检年度', '评分等级').annotate(count=Count("id")))
    r = dict()
    for i in tmp:
        if i["辖区"] not in r:
            r[i["辖区"]] = {}
        if i["抽检年度"] not in r[i["辖区"]]:
            r[i["辖区"]][i["抽检年度"]] = {"A": 0, "B": 0, "C": 0, "D": 0}
        r[i["辖区"]][i["抽检年度"]][i["评分等级"]] = i["count"]
    r["厦门市"] = {}
    for i in tmp1:
        if i["抽检年度"] not in r["厦门市"]:
            r["厦门市"][i["抽检年度"]] = {"A": 0, "B": 0, "C": 0, "D": 0}
        r["厦门市"][i["抽检年度"]][i["评分等级"]] = i["count"]
    response["data"]["class"] = r

    # response["data"]["total"] = list(Pingfen.objects.filter(行业=industry).values())

    response |= {
        "code": 2000,
        "msg": "success"
    }

    return JsonResponse(response)
